package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.FriendCircleDomain;
import com.sendpo.zjx.sendpo.domain.MerchatsmianDynimcDomain;
import com.sendpo.zjx.sendpo.fragment.YanchuFragment_Saishi;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.imagewatcher.ImageWatcher;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 朱俊鑫 on 2018
 */

public class MerchantFriendCircleListActivity extends AppCompatActivity {

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.fabu_bt)
    RelativeLayout fabuBt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    @BindView(R.id.v_image_watcher)
    ImageWatcher vImageWatcher;
    @BindView(R.id.pulltofresh)
    PullToRefreshLayout pulltofresh;
    LinearLayoutManager lm;
    private RecylcerAdaper adpter;
    private  int pagenow=1;
    private int merchantsId=0;
    public static  final int FINSIH=1001;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchatsmainuserfriendcircle);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        merchantsId=getIntent().getIntExtra("merchantsId",0);
        initComponent();

    }
    private void initComponent() {
        lm=new LinearLayoutManager(this, OrientationHelper.VERTICAL,false);
        recyclerview.setLayoutManager(lm);
        List<FriendCircleDomain.DataBean> dataBeans=new ArrayList<>();
        recyclerview.setAdapter(adpter = new RecylcerAdaper(MerchantFriendCircleListActivity.this,dataBeans));
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                pagenow=1;
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    query(pagenow,0);
                }else{
                    query(pagenow,userList.get(0).getUserId());
                }
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                pagenow++;
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    append(pagenow,0);
                }else{
                    append(pagenow,userList.get(0).getUserId());
                }
            }
        });
        pulltofresh.autoRefresh();
    }

    @OnClick(value = {R.id.backbt,R.id.fabu_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.fabu_bt:
                Intent intent=new Intent(this,MerchantFriendCircleSubmitActivity.class);
                startActivityForResult(intent,FINSIH);
                break;
        }
    }


    public void query(int pagenow,final int userId) {
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.usefriendcircleById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                System.out.println("****************"+result);
                Gson gson = new Gson();
                FriendCircleDomain domain = gson.fromJson(result, FriendCircleDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(MerchantFriendCircleListActivity.this,domain.getData()));

                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow,final int userId) {
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.usefriendcircleById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                System.out.println("****************"+result);
                Gson gson = new Gson();
                FriendCircleDomain domain = gson.fromJson(result, FriendCircleDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(MerchantFriendCircleListActivity.this,domain.getData()));

                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }



    public class RecylcerAdaper extends  RecyclerView.Adapter<RecyclerView.ViewHolder>{
        public List<FriendCircleDomain.DataBean> dataBeen;
        public LayoutInflater inflater;
        public RecylcerAdaper(Context context, List<FriendCircleDomain.DataBean> dataBeen)
        {
            this.inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new IndexHoler(this.inflater.inflate(R.layout.layout_yanchusaishi_listitem, parent, false));
        }


        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            final IndexHoler ih= (IndexHoler) holder;
            final FriendCircleDomain.DataBean dataBean =dataBeen.get(position);
            Glide.with(MerchantFriendCircleListActivity.this)
                    .load(dataBean.getUseravatar())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .centerCrop()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.head_icon.setImageBitmap(resource);
                        }
                    });
            ih.head_icon.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap();
                    map.put("id", dataBean.getUserId());
                    Tools.redirectActivity(MerchantFriendCircleListActivity.this, StoreMainAllProduceActivity.class, map);
                }
            });
            ih.title.setText("" + dataBean.getUserFriendscircleTag());
            ih.content.setText("" + dataBean.getUserFriendscircleText());
            ih.watchnum.setText("" + dataBean.getUserFriendscircleLooknumber());
            ih.location.setText("" + dataBean.getUserArea());
            ih.all_ll.removeAllViews();
            List<String> imgs = dataBean.getImgs();
            if (imgs != null && imgs.size() != 0) {
                final List<String> ivs_s = new ArrayList<>();
                final List<ImageView> ivs = new ArrayList<>();
                for (String img : imgs) {
                    final ImageView iv = new ImageView(MerchantFriendCircleListActivity.this);
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(158), DensityUtil.dip2px(158));
                    lp.setMargins(0, 0, DensityUtil.dip2px(10), 0);
                    iv.setLayoutParams(lp);
                    iv.setBackgroundColor(getResources().getColor(R.color.default_lightgray));
                    Glide.with(MerchantFriendCircleListActivity.this)
                            .load(img)
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .override(500, 500)
                            .into(iv);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            vImageWatcher.show(iv, ivs, ivs_s);
                        }
                    });
                    ivs.add(iv);
                    ivs_s.add(img);
                    ih.all_ll.addView(iv);
                }
            }


            if (dataBean.isUserFriendscircleState()) {
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);

            } else {
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);

            }

            ih.goods_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    List<User> userList = Xutils.queryAll(MerchantFriendCircleListActivity.this.getApplication(), User.class);

                    if (userList == null || userList.size() == 0) {
                        Tools.redirectActivity(MerchantFriendCircleListActivity.this, LoginActivity.class);
                        return;
                    }

                    if (dataBean.isUserFriendscircleState()) {
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);
                        dataBean.setUserFriendscircleState(false);
                        int count = Integer.parseInt(ih.goood_tv.getText().toString().trim() + "");
                        count--;
                        ih.goood_tv.setText(count + "");
                        nofocus(userList.get(0).getUserId() + "", dataBean.getUserFriendscircleId() + "");
                    } else {
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
                        dataBean.setUserFriendscircleState(true);
                        int count = Integer.parseInt(ih.goood_tv.getText().toString().trim() + "");
                        count++;
                        ih.goood_tv.setText(count + "");
                        focus(userList.get(0).getUserId() + "", dataBean.getUserFriendscircleId() + "");
                    }
                }
            });
            ih.goood_tv.setText("" + dataBean.getDynamicPraiseCount());
            System.out.println("*********************"+dataBean.getGuestcount());
            ih.guest_tv.setText("" + dataBean.getGuestcount());
            ih.tag_ll.removeAllViews();
            String officialTag = dataBean.getUserFriendscircleOfficialTag();
            if (TextUtils.isEmpty(officialTag)) {
                return;
            }
            ih.guest_tv.setText("" + dataBean.getGuestcount());
            ih.guest_bt.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View paramAnonymousView)
                {
                    Map<String,Object> map = new HashMap();
                    map.put("data", dataBean);
                    Tools.redirectActivity(MerchantFriendCircleListActivity.this, UserActiveInfoActvitiy.class, map);
                }
            });
            ih.watch_bt.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View paramAnonymousView)
                {
                    Map<String,Object> map = new HashMap();
                    map.put("data", dataBean);
                    Tools.redirectActivity(MerchantFriendCircleListActivity.this, UserActiveInfoActvitiy.class, map);
                }
            });
            ih.rootView.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View paramAnonymousView)
                {
                    Map<String,Object> map = new HashMap();
                    map.put("data", dataBean);
                    Tools.redirectActivity(MerchantFriendCircleListActivity.this, UserActiveInfoActvitiy.class, map);
                }
            });
            ih.all_ll.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View paramAnonymousView)
                {
                    Map<String,Object> map = new HashMap();
                    map.put("data", dataBeen);
                    Tools.redirectActivity(MerchantFriendCircleListActivity.this, UserActiveInfoActvitiy.class, map);
                }
            });
            ih.address.setText("" + dataBean.getUserAddress());
            String[]  strings =officialTag.split(",");
            if (strings==null||strings.length==0) {
                return;
            }
            for(int i=0;i<strings.length;i++){
                String str=strings[i];
                TextView textView = new TextView(MerchantFriendCircleListActivity.this);
                textView.setText("" + str);
                LinearLayout.LayoutParams  lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(35.0F), DensityUtil.dip2px(20.0F));
                lp.setMargins(DensityUtil.dip2px(5.0F), DensityUtil.dip2px(5.0F), DensityUtil.dip2px(5.0F), DensityUtil.dip2px(5.0F));
                textView.setLayoutParams(lp);
                textView.setTextSize(8.0F);
                textView .setGravity(17);
                textView.setTextColor(getResources().getColor(R.color.white));
                if(str.equals("100人")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_yellow1));
                }else if(str.equals("300人")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_yellow1));
                }else if(str.equals("500人")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_yellow1));
                }else if(str.equals("1000人")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_yellow1));
                }else if(str.equals("一起狂欢")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_blue));
                }else if(str.equals("靓女靓仔")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_theme));
                }else if(str.equals("机会难得")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_theme));
                }else if(str.equals("一起哈皮")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_theme));
                } else if(str.equals("免费")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_blue));
                }else if(str.equals("收费")){
                    textView.setBackgroundColor(getResources().getColor(R.color.default_blue));
                }
                ih.tag_ll.addView(textView);
            }
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }
        public void focus(String userId, String userFriendscircleId) {
            HashMap localHashMap = new HashMap();
            localHashMap.put("userId", "" + userId);
            localHashMap.put("userFriendscircleId", userFriendscircleId);
            Xutils.POST(HttpUrl.friendcirclepraiseAdd, localHashMap, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        public void nofocus(String userId, String userFriendscircleId) {
            HashMap localHashMap = new HashMap();
            localHashMap.put("userId", "" + userId);
            localHashMap.put("userFriendscircleId", userFriendscircleId);
            Xutils.POST(HttpUrl.friendcirclepraiseDelete, localHashMap, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }
        public void initAppend(List<FriendCircleDomain.DataBean> paramList) {
            this.dataBeen.addAll(paramList);
            notifyDataSetChanged();
        }

        public void initRefresh(List<FriendCircleDomain.DataBean> paramList) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(paramList);
            notifyDataSetChanged();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public TextView address;
            public LinearLayout all_ll;
            public TextView content;
            public RelativeLayout goods_bt;
            public ImageView goods_iv;
            public TextView goood_tv;
            public RelativeLayout guest_bt;
            public TextView guest_tv;
            public CircleImageView head_icon;
            public TextView location;
            public View rootView;
            public LinearLayout tag_ll;
            public TextView title;
            public RelativeLayout watch_bt;
            public TextView watchnum;
            public IndexHoler(View rootView) {
                super(rootView);
                this.address = rootView.findViewById(R.id.address);
                this.rootView = rootView;
                this.head_icon = rootView.findViewById(R.id.head_icon);
                this.title = rootView.findViewById(R.id.title);
                this.all_ll =  rootView.findViewById(R.id.all_ll);
                this.watchnum = rootView.findViewById(R.id.watchnum);
                this.goods_iv = rootView.findViewById(R.id.goods_iv);
                this.goods_bt = rootView.findViewById(R.id.goods_bt);
                this.goood_tv =  rootView.findViewById(R.id.goood_tv);
                this.guest_bt = rootView.findViewById(R.id.guest_bt);
                this.watch_bt = rootView.findViewById(R.id.watch_bt);
                this.guest_tv =rootView.findViewById(R.id.guest_tv);
                this.content=rootView.findViewById(R.id.content);
                this.location =rootView.findViewById(R.id.location);
                this.tag_ll = rootView.findViewById(R.id.tag_ll);
            }
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK){
            return;
        }
        switch (requestCode){
            case FINSIH:
                pulltofresh.autoRefresh();
                break;
        }
    }
}
